package parser;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * @author 石小俊
 */
public class DOMParser {

    public static void main(String[] args) {
        // 创建DOM工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {
            // 获取解析器
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 解析文档
            Document document = builder.parse(DOMParser.class.getClassLoader().getResourceAsStream("students.xml"));

            // 根据解析的结果进行操作
            // 获取根标签
            Element root = document.getDocumentElement();
            System.out.println("标签名:"+root.getTagName());
            System.out.println("no属性值:"+root.getAttribute("no"));
            // 获取所有子节点
            NodeList childNodes = root.getChildNodes();
            System.out.println("子节点数量:"+childNodes.getLength());
            for(int i = 0; i < childNodes.getLength(); i++){
                // 取出当前迭代的节点
                Node node = childNodes.item(i);
                if(node.getNodeType() == Node.ELEMENT_NODE){
                    // 元素节点
                    Element student = (Element) node;
                    System.out.println("标签名:"+student.getTagName());
                    // 遍历所有属性
                    NamedNodeMap attributes = student.getAttributes();
                    for(int j = 0; j < attributes.getLength(); j++){
                        System.out.println(attributes.item(j));
                    }
                    // 获取所有子节点
                    NodeList childNodes2 = student.getChildNodes();
                    System.out.println("子节点数量:"+childNodes2.getLength());
                    for(int j = 0; j < childNodes2.getLength();j++){
                        Node item = childNodes2.item(j);
                        if(item.getNodeType() == Node.ELEMENT_NODE){
                            Element name = (Element) item;
                            System.out.println(name.getTagName());
                            System.out.println("name标签体的内容:"+name.getTextContent());
                        }
                    }
                }

                if(node.getNodeType() == Node.TEXT_NODE){
                    // 文本节点
                    System.out.println("文本节点内容:"+node.getTextContent());
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

}
